import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class MyApp extends JFrame{
	private static final long serialVersionUID = 1L;
	private JTextField urlTextField = new JTextField(40); // component index 0
	private JButton fetchButton = new JButton("Fetch");
	private JButton genAndSaveButton = new JButton("Save As"); // component index 2
	private JButton toggleButton = new JButton("Select All");
	private JButton clearButton = new JButton("Clear All");
	public MyApp() {
		super("www.sharingglaxy.com/main.html");
		setLayout(new FlowLayout());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		add(urlTextField);// component index 0 --used
		add(fetchButton);// component index 1 --used
		add(genAndSaveButton);// component index 2 --used
		add(toggleButton);// component index 3
		add(clearButton);
		fetchButton.addActionListener(new FetchURLSAndAddCheckBoxesToFrame());
		genAndSaveButton.addActionListener(new GenarateAndSaveAsPlayList());
		genAndSaveButton.setVisible(false);
		genAndSaveButton.setToolTipText("Save playlist with selected files");
		toggleButton.addActionListener(new ToggleCheckBoxesButtonActionListner());
		clearButton.addActionListener(new ClearAllButtonListner());
		addWindowFocusListener(new MyWindowListner());
		setSize(Toolkit.getDefaultToolkit().getScreenSize().width/2, Toolkit.getDefaultToolkit().getScreenSize().height/2);
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new MyApp();
	}
}
class ClearAllButtonListner implements ActionListener{
	@Override
	public void actionPerformed(ActionEvent e) {
		JButton source = (JButton)e.getSource();
		for(Component component : source.getParent().getComponents()){
			if (component instanceof JCheckBox) {
				source.getParent().remove(component);
			}
		}
		source.getParent().getComponent(2).setVisible(false);
		source.getParent().validate();
		for(ActionListener actionListener : source.getParent().getComponent(1).getListeners(ActionListener.class)){
            try {
                actionListener.getClass().getMethod("clearFetchedUrls", (Class<?>[]) null).invoke(actionListener, (Object[]) null);
            } catch (Throwable ex){}
        }
	}
}
class MyWindowListner extends WindowAdapter{
	@Override
	public void windowGainedFocus(WindowEvent e) {
		JTextField component = (JTextField) ((MyApp)e.getSource()).getContentPane().getComponent(0);
		String commponetText = component.getText();
		if(commponetText != null){
			String cbText = readClipboardContent();
			if(cbText != null && !"".equals(cbText.trim()) && cbText.toLowerCase().startsWith("http://")){
				component.setText(cbText);
			}
		}
	};
	private String readClipboardContent(){
		Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
		if(transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)){
			try {
				return (String)transferable.getTransferData(DataFlavor.stringFlavor);
			} catch (Throwable e1) {} 
		}
		return null;
	}
}

class ToggleCheckBoxesButtonActionListner implements ActionListener{
	@Override
	public void actionPerformed(ActionEvent e) {
		boolean visible = false;
		JButton source = (JButton)e.getSource();
		boolean checked = false;
		if(source.getText().equals("Select All")) checked = true;
		for(Component component : source.getParent().getComponents()){
			if (component instanceof JCheckBox) {
				((JCheckBox) component).setSelected(checked);
				if(((JCheckBox) component).isSelected()){
					visible = true;
				}
			}
		}
		if(checked){
			source.setText("DeSelect All");
		}else{
			source.setText("Select All");
		}
		source.getParent().getComponent(2).setVisible(visible);
		source.getParent().validate();
	}
}
class FetchURLSAndAddCheckBoxesToFrame implements ActionListener{
	private Set<String> urlFetched;
	public FetchURLSAndAddCheckBoxesToFrame(){
		urlFetched = new HashSet<String>();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		JButton source = (JButton)e.getSource();
		String urlText = ((JTextField) source.getParent().getComponent(0)).getText();
		if(urlText == null || "".equals(urlText.trim()) || urlFetched.contains(urlText.toLowerCase())) return;
		List<String> urLs2 = null;
		try{
			urLs2 = new FetchURLS().getMediaUrls(urlText);
			urlFetched.add(urlText.toLowerCase());
		}catch (Throwable throwable) {
			StringWriter sw = new StringWriter();
			throwable.printStackTrace(new PrintWriter(sw));
			JOptionPane.showMessageDialog(source.getParent(), sw.toString(),"Error" , JOptionPane.ERROR_MESSAGE);
		}
		if(urLs2 != null)
		for (String string : urLs2) {
			JCheckBox checkBox = new JCheckBox(string);
			checkBox.setToolTipText(string);
			int lastIndexOf = string.lastIndexOf("/");
			if(lastIndexOf != -1){
				checkBox.setText(string.substring(lastIndexOf + 1));
			}	
			source.getParent().add(checkBox);	
			checkBox.addChangeListener(new CheckBoxChangeListener());
		}
		source.getParent().validate();
	}
	public void clearFetchedUrls(){
		urlFetched.clear();
	}
}
class CheckBoxChangeListener implements ChangeListener{
	@Override
	public void stateChanged(ChangeEvent e) {
		boolean visible = false;
		JCheckBox source = (JCheckBox) e.getSource();
		if(source.isSelected()){
			visible = true;
		}else{
			for(Component component : source.getParent().getComponents()){
				if (component instanceof JCheckBox) {
					if(((JCheckBox) component).isSelected()){
						visible = true;
						break;
					}
				}
			}
		}
		source.getParent().getComponent(2).setVisible(visible);
		source.getParent().validate();
	}
}

class GenarateAndSaveAsPlayList implements ActionListener{
	@Override
	public void actionPerformed(ActionEvent e) {
		JButton source = (JButton) e.getSource();
		Component[] components = source.getParent().getComponents();
		List<String> selectedUrls = new ArrayList<String>();
		for(Component component : components){
			if (component instanceof JCheckBox) {
				JCheckBox checkBox = (JCheckBox) component;
				if(checkBox.isSelected()){
					selectedUrls.add(checkBox.getToolTipText());
				}
			}
		}
		JFileChooser chooser = new JFileChooser(System.getProperty("user.home"));
		int returnValue = chooser.showSaveDialog(source.getParent());
		if(returnValue == JFileChooser.APPROVE_OPTION){
			try {
				new GenrateXSPF(selectedUrls).writeXSPF2File(chooser.getSelectedFile());
				JOptionPane.showMessageDialog(source.getParent(), "Saved Sucessfully", "Save Operation", JOptionPane.CLOSED_OPTION);
			} catch (Throwable throwable) {
				StringWriter sw = new StringWriter();
				throwable.printStackTrace(new PrintWriter(sw));
				JOptionPane.showMessageDialog(source.getParent(), sw.toString(),"Error while save" , JOptionPane.ERROR_MESSAGE);
			}
		}
			
		
	}
}